﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mall.Application.System
{
    public class RoleService : IRoleService, ITransient
    {
        private readonly IRepository<RolePermission> _rolePermissionRepository;
        private readonly IRepository<Role> _roleRepository;
        public RoleService(IRepository<RolePermission> rolePermissionRepository, IRepository<Role> roleRepository)
        {
            _rolePermissionRepository = rolePermissionRepository;
            _roleRepository = roleRepository;
        }

        public PagedList<Role> GetPagedList(RoleDtoInput input)
        {
            var query = _roleRepository.DetachedEntities;
            //搜索

            var list = query
               .OrderByDescending(x => x.Id)
               .ToPagedList(input.Page, input.Limit);

            return list;
        }

        public void GrantResource(int roleId, int[] pids)
        {
            _rolePermissionRepository.Entities.Where(x => x.RoleId == roleId).ExecuteDelete();  //ExecuteDelete：EF7的批量删除
            List<RolePermission> permissions = new();
            foreach (var p in pids)
            {
                var rp = new RolePermission { RoleId = roleId, PermissionId = p };
                permissions.Add(rp);
            }
            _rolePermissionRepository.Insert(permissions);
        }
    }
}